/*
 * Copyright © 2011 Breachwalls & Company Inc. and other authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.breachwalls.h2p.platform.workflow.process;

import java.util.List;

import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;

import com.breachwalls.h2p.platform.workflow.business.BusinessInstance;

/**
 * 汎用的なプロセスサービス.
 * @author Ken Todoroki
 * @version $Revision$
 */
public class GenericProcessService extends ProcessServiceSupport implements ProcessService {

    protected ProcessInstance startProcessInstanceByBusinessInstance(BusinessInstance instance) {
        ProcessInstance pi = getRuntimeService().startProcessInstanceByKey(instance.getFlowName(),
            instance.getId(), instance.getVariables());
        return pi;
    }

    protected ProcessInstance getProcessInstanceByBusinessInstance(BusinessInstance instance) {
        ProcessInstanceQuery query = getRuntimeService().createProcessInstanceQuery();
        query.processInstanceBusinessKey(instance.getId(), instance.getFlowName());
        return query.singleResult();
    }

    protected List<Task> getTasksByProcessInstance(ProcessInstance instance) {
        TaskQuery query = getTaskService().createTaskQuery();
        query.processInstanceId(instance.getId());
        return query.list();
    }

    @Override
    public void start(BusinessInstance instance) {
        // ワークフローの開始
        ProcessInstance pi = startProcessInstanceByBusinessInstance(instance);

        // タスク処理を実行
        List<Task> tasks = getTasksByProcessInstance(pi);
        for (Task task : tasks) {
            getTaskService().complete(task.getId(), instance.getVariables());
        }
    }

    @Override
    public void proceed(BusinessInstance instance) {
        // プロセスインスタンスの取得
        ProcessInstance pi = getProcessInstanceByBusinessInstance(instance);

        // タスクの取得と実行
        List<Task> tasks = getTasksByProcessInstance(pi);
        for (Task task : tasks) {
            getTaskService().complete(task.getId(), instance.getVariables());
        }
    }

}
